package com.shop.zzh.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.zzh.entity.User;
import com.shop.zzh.mbg.mapper.UserLogMapper;
import com.shop.zzh.mbg.model.UserLog;
import com.shop.zzh.result.ContentResultForm;
import com.shop.zzh.result.ResultForm;
import com.shop.zzh.service.UserService;
import com.shop.zzh.utils.IpUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @program: shop
 * @description: 控制类
 * @author: zhuzh
 * @create: 2019-11-19 21:00
 **/
@RestController
@RequestMapping("/zzh/zc")
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private RabbitTemplate rabbitTemplate;
	@Autowired
	private Environment env;
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private UserLogMapper userLogMapper;
	@Value("${jwt.tokenHeader}")
	private String tokenHeader;
	@Value("${jwt.tokenHead}")
	private String tokenHead;

	@ApiOperation(value = "前台登录以后返回token")
	@PostMapping("/login.do")
	public ContentResultForm<User> login(User user, HttpServletRequest request){
		ContentResultForm contentResultForm = null;
		user.setPassword(user.getPassword());
		String token = userService.login(user);
		Map<String, Object> tokenMap = new HashMap<>();
		if(token!=null){
			try {
				//登录日志
				UserLog userLog=new UserLog();
				userLog.setUserLogId(UUID.randomUUID().toString());
				userLog.setUserLogCz("登录");
				userLog.setUserLogInterfaceName("/zzh/zc/login.do");
				userLog.setUserLogYh(objectMapper.writeValueAsString(user));
				userLog.setUserLogIp(IpUtils.getIpAddr(request));
				userLog.setUserLogTime(new Date());
				userLogMapper.insert(userLog);

				rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
				rabbitTemplate.setExchange(env.getProperty("log.user.exchange.name"));
				rabbitTemplate.setRoutingKey(env.getProperty("log.user.routing.key.name"));
				//setDeliveryMode(MessageDeliveryMode.PERSISTENT设置消息持久化
				Message message=MessageBuilder.withBody(objectMapper.writeValueAsBytes(userLog)).setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
				message.getMessageProperties().setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, MessageProperties.CONTENT_TYPE_JSON);
				rabbitTemplate.convertAndSend(message);
				tokenMap.put("token", token);
				tokenMap.put("tokenHead", tokenHead);
				tokenMap.put("user",user);
				tokenMap.put("message","登录成功");
				contentResultForm = new ContentResultForm(true,tokenMap);
			}catch (Exception e){
				e.printStackTrace();
			}
		}else{
			tokenMap.put("message","用户名或密码错误");
			contentResultForm = new ContentResultForm(false,tokenMap);
		}

		return contentResultForm;
	}

	@ApiOperation(value = "后台登录以后返回token")
	@PostMapping("/welComeLogin.do")
	public ContentResultForm<User> welComeLogin(String login, String pwd){
		User user =  new User();
		user.setUserName(login);
		ContentResultForm contentResultForm = null;
		user.setPassword(pwd);
		String token = userService.login(user);
		if(token!=null){
			contentResultForm = new ContentResultForm(true,user);
		}else{
			contentResultForm = new ContentResultForm(false,user);
		}
		return contentResultForm;
	}

	@ApiOperation(value="注册用户")
	@PostMapping("/register.do")
	public ResultForm register(String username,String pwd){
		User user = new User();
		user.setId(UUID.randomUUID().toString());
		user.setUserName(username);
		//将密码进行加密操作
		String encodePassword = passwordEncoder.encode(pwd);
		user.setPassword(encodePassword);
		user.setCreateTime(new Date());
		user.setPrivilege("1");
		user.setPoints(0);
		userService.register(user);
		return new ResultForm(true,"注册成功");
	}
	@ApiOperation(value="查看是否存在该用户")
	@PostMapping("/checkUser.do")
	public ResultForm checkUser(String username){
		boolean bool = true;
		User user = userService.selectOnByUserName(username);
		if(user!=null){
			bool = false;
		}
		return new ResultForm(bool,"核查消息");
	}
}
